<template>
  <el-dialog :title="title" :visible.sync="visible" width="680px" append-to-body @open="onOpen" @close="onClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" type="number" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio label="01">男</el-radio>
              <el-radio label="02">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="身份证信息" prop="identityCard">
            <el-input v-model="form.identityCard" placeholder="请输入身份证信息" @input="getAgeByIdCard"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属关系" prop="ownership">
            <el-select v-model="form.ownership" placeholder="所属关系" clearable>
              <el-option
                v-for="dict in dict.type.ownership"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属老人" prop="elderlyInfoId">
            <el-select
              v-model="form.elderlyInfoId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="optionsLoading"
              @change="onSelectChange"
            >
              <el-option
                v-for="item in options"
                :key="item.elderlyInfoId"
                :label="item.name"
                :value="item.elderlyInfoId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="form.phone" type="number" placeholder="请输入电话号码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4 }"
              placeholder="请输入备注"
              v-model="form.remark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import dayjs from "dayjs";
import cascader from "@/components/cascader/index.vue";
import { add, update } from "@/api/pension/supervisionInfo";
import { queryList } from "@/api/pension/elderlyInfo";

export default {
  name: "add-modal",
  dicts: ['ownership'],
  components: {cascader},
  props: {
    value: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
      return {
        optionsLoading: false,
        options: [],
        // 表单参数
        defaultForm: {
          name: '',
          age: '',
          gender: '01',
          identityCard: '',
          ownership: '',
          phone: '',
          remark: '',
          elderlyInfoId:''
        },
        form: {
          name: '',
          age: '',
          gender: '01',
          identityCard: '',
          ownership: '',
          phone: '',
          remark: '',
          elderlyInfoId:''
        },
        // 表单校验
        rules: {
          elderlyInfoId: [
            { required: true, message: "必填项不能为空", trigger: "blur" }
          ],
          name: [
            { required: true, message: "必填项不能为空", trigger: "blur" }
          ],
          age: [
            { required: true, message: "必填项不能为空", trigger: "blur" }
          ],
          gender: [
            { required: true, message: "必填项不能为空", trigger: "change" }
          ],
          identityCard: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback('必填项不能为空')
                } else if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
                  callback('身份证格式错误')
                } else {
                  callback()
                }
              },
              trigger: "blur"
            }
          ],
          ownership: [
            { required: true, message: "必填项不能为空", trigger: "blur" }
          ],
          phone: [
            { required: true, message: "必填项不能为空", trigger: "blur" }
          ],
        }
      }
  },
  computed: {
    title() {
        return !!this.detail ? '修改' : '新增'
    },
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  methods: {
    getAgeByIdCard(idCard) {
      if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idCard)) return
      const birthday = idCard.substring(6, 10) + '-' + idCard.substring(10, 12) + '-' + idCard.substring(12, 14);

      this.form.age = dayjs().diff(dayjs(birthday), 'year')
      this.$refs.form.validateField('age')
    },
    onSelectChange(val) {
      const option = this.options.find(item => item.elderlyInfoId === val)
      if (option) {
        this.form.elderlyInfoId = option.elderlyInfoId;
        this.form.elderlyName = option.name;
      }else{
        this.form.elderlyInfoId = null;
        this.form.elderlyName = null;
      }
    },
    // 远程搜索
    remoteMethod(query) {
      if (query !== '') {
        this.optionsLoading = true;
        queryList({name:query}).then(response => {
          this.options = response.data;
          this.optionsLoading = false;
        });
      } else {
        this.options = [];
      }
    },
    onOpen() {
      this.remoteMethod();
      this.form.supervisionInfoId = ''
      this.form = Object.assign(this.form, this.detail || this.defaultForm)
    },
    onClose() {
      this.$refs.form.resetFields()
    },
    async submitForm() {
      const state = await this.$refs.form.validate();
      if (!state) return
      const isEdit = !!this.form.supervisionInfoId
      const API = isEdit ? update : add

      API(this.form).then((response) => {
        this.$modal.msgSuccess(isEdit ? "修改成功" : "新增成功");
        this.$emit('refresh')
        this.cancel();
      });
    },
    cancel() {
      this.visible = false
    }
  }
}
</script>
<style scoped lang="scss">

</style>
